#pragma once
#include<iostream>
#include<sys/types.h>
#include<sys/time.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/stat.h>
#include<cstdio>
#include<cstring>
#include<fcntl.h>
#include<stdlib.h>
#include<signal.h>
#include<pthread.h>
#include <numeric>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<memory>
#include<unordered_map>
#include<unordered_set>
#include<queue>
#include<vector>
#include<utility> //类pair的声明
#include<arpa/inet.h>
#include<sys/wait.h>
#include<functional>
#include <semaphore.h>
#include<jsoncpp/json/json.h>
#include<sys/select.h>
#include"task.hpp"
using namespace std;
class Channel
{
public:
    pid_t _pid;
    string _name;
    int _wfd;
public:
    Channel(pid_t pid,string name,int wfd)
    :_pid(pid),_name(name),_wfd(wfd){}
};
void Work(int rfd)
{
    while(1)
    {
       int number=0;
       int n=read(rfd,&number,sizeof(int));
      if(n>0)
      {
        execute[number-1]();
      }
      else
      break;
    }
}
void CleanPid(const vector<Channel>&ret)
{
    int n=ret.size();
    for(int i=1;i<=n;i++)
    {
        cout<<"关闭"<<ret[i-1]._name<<ret[i-1]._wfd<<"号文件描述符"<<endl; 
        close(ret[i-1]._wfd);
    }
    for(int i=1;i<=n;i++)
    {
        
        waitpid(ret[i-1]._pid,nullptr,0);
        cout<<ret[i-1]._name<<"已退出"<<endl;
    }
}
void CreateChannels(vector<Channel> &ret)
{
    for (int i = 0; i < 4; i++)
    {
        int Pipe[2];
        pipe(Pipe);
        pid_t id = fork();
        if (id == 0)
        {
            close(Pipe[1]);
            Work(Pipe[0]);
            close(Pipe[0]);
            exit(0);
        }
        else
        {
            close(Pipe[0]);
            string name = "进程";
            name += to_string(i + 1);
            ret.push_back(Channel(id, name, Pipe[1]));
        }
    }
}
void RunTask(const vector<Channel>&ret)
{
     while (1)
    {
        cout << "在1-4号任务中选择一个";
        int select;
        cin >> select;
        cout << "在1-4号进程中选择分配给哪个进程";
        int number;
        cin >> number;
        write(ret[number]._wfd, &select, sizeof(int));
        sleep(1);
        cout << "是否退出,0:退出 1:不退出";
        int exit;
        cin >> exit;
        if (!exit)
            break;
    }
}